<template>
  <div class="bom-container">
    <!-- 顶部搜索区域 -->
    <div class="search-section">
      <div class="search-row">
        <div class="search-item">
          <label>编码:</label>
          <el-input v-model="searchForm.bomCode" placeholder="请选择编码" class="search-input" clearable
            @keyup.enter="handleSearch" />
        </div>
        <div class="search-actions">
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </div>
      </div>
      <div class="action-row">
        <div class="left-actions">
          <el-button @click="expandAll">展开全部</el-button>
          <el-button @click="collapseAll">折叠全部</el-button>

        </div>
        <div class="right-actions">
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <el-button type="success" @click="handleExport">导出</el-button>
          <el-button type="primary" @click="handleImport">
            <el-icon>
              <Upload />
            </el-icon>
            导入
          </el-button>
          <el-icon class="refresh-icon" @click="refreshData">
            <Refresh />
          </el-icon>
          <el-icon class="setting-icon">
            <Setting />
          </el-icon>
          <el-icon class="fullscreen-icon">
            <FullScreen />
          </el-icon>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 - 表格形式 -->
    <div class="main-content">
      <div class="table-container">
        <el-table :data="bomTableData" v-loading="tableLoading" class="data-table" border stripe row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :default-expand-all="false"
          ref="bomTableRef">
          <el-table-column prop="bomCode" label="编码" width="200" align="left">
            <template #default="scope">
              <div class="code-cell">
                <span>{{ scope.row.bomCode }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="bomName" label="名称" width="120" align="center" />
          <el-table-column prop="version" label="版本" width="80" align="center" />
          <el-table-column prop="itemTypeName" label="类型" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getTagType(scope.row.itemTypeId)" size="small" class="type-tag">
                {{ scope.row.itemTypeName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="bomLevel" label="阶别" width="80" align="center">
            <template #default="scope">
              <el-tag :type="getLevelTagType(scope.row.bomLevel)" size="small" round class="level-tag">
                {{ scope.row.bomLevel }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="processCode" label="工序编码" width="140" align="center" />
          <el-table-column prop="processName" label="工序名称" width="140" align="center" />
          <el-table-column prop="useQty" label="用量" width="80" align="center" />
          <el-table-column prop="bomMsg" label="描述" width="130" align="center" />
          <el-table-column prop="addProp" label="创建人" width="120" align="center" />
          <el-table-column prop="addTime" label="创建时间" width="150" align="center" />
          <el-table-column label="操作" width="250" align="center" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button type="text" @click="handleAddSub(scope.row)" class="action-link">
                  添加下级
                </el-button>
                <el-button type="text" @click="handleEdit(scope.row)" class="action-link">
                  编辑
                </el-button>
                <el-button type="text" @click="handleDelete(scope.row)" class="action-link delete-link">
                  删除
                </el-button>
                <el-button v-if="scope.row.bomLevel === 0" type="text" @click="handleBindProduct(scope.row)"
                  class="action-link">
                  绑定产品
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="resetForm"
      :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="bom-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="编码" prop="bomCode" required>
              <el-select v-model="form.bomCode" placeholder="请选择产品物料" style="width: 100%" clearable :disabled="isEdit"
                filterable @change="handleCodeChange">
                <el-option v-for="material in availableMaterials" :key="material.id" :label="material.materialsName"
                  :value="material.materialsCode">
                  <div class="material-option">
                    <el-tag :type="getTagType(material.itemTypeId)" size="small" class="option-tag">
                      {{ material.itemTypeName }}
                    </el-tag>
                    <span class="material-name">{{ material.materialsName }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="bomName" required>
              <el-input v-model="form.bomName" placeholder="请输入名称" clearable
                :class="{ 'is-auto-filled': isNameAutoFilled }" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="版本" prop="version">
              <el-input v-model="form.version" placeholder="请输入版本" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="BOM层级" prop="bomLevel">
              <el-input-number v-model="form.bomLevel" :min="0" placeholder="请输入层级" style="width: 100%"
                :disabled="isEdit" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工序" prop="processId">
              <el-select v-model="form.processId" placeholder="请选择工序" style="width: 100%" clearable filterable>
                <el-option v-for="process in processList" :key="process.id"
                  :label="`(${process.processCode})${process.processName}`" :value="process.id">
                  <div class="process-option">
                    <span class="process-code">{{ process.processCode }}</span>
                    <span class="process-name">{{ process.processName }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用量" prop="useQty">
              <el-input-number v-model="form.useQty" :min="0" :precision="2" placeholder="请输入用量" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述" prop="bomMsg">
          <el-input v-model="form.bomMsg" type="textarea" :rows="3" placeholder="请输入描述" resize="both"
            style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 物料选择器对话框 -->
    <el-dialog v-model="showMaterialSelector" title="选择下级" width="1700px" :close-on-click-modal="false">
      <div class="dual-panel-container">
        <!-- 左侧可用物料列表 -->
        <div class="list-panel">
          <div class="panel-header">
            <div class="header-left">
              <span class="item-count">{{ availableMaterials.length }}项</span>
              <div class="legend">
                <span class="legend-item">
                  <span class="legend-color disabled-text"></span>
                  <span>已选物料</span>
                </span>
                <span class="legend-item">
                  <span class="legend-color disabled-text-current"></span>
                  <span>当前BOM</span>
                </span>
              </div>
            </div>
            <div class="search-box">
              <el-input v-model="leftSearchText" placeholder="请输入搜索内容" size="small" clearable>
                <template #prefix>
                  <el-icon>
                    <Search />
                  </el-icon>
                </template>
              </el-input>
              <el-icon class="refresh-icon" @click="refreshMaterials">
                <Refresh />
              </el-icon>
            </div>
          </div>
          <div class="table-container">
            <el-table :data="filteredAvailableMaterials" @selection-change="handleLeftSelectionChange"
              class="material-table" border stripe :row-class-name="getRowClassName">
              <el-table-column type="selection" width="55" :selectable="isSelectable" />
              <el-table-column prop="materialsCode" label="编码" width="120">
                <template #default="scope">
                  <span :class="{
                    'disabled-text': !isSelectable(scope.row) && !isCurrentBomMaterial(scope.row.materialsCode),
                    'disabled-text-current': !isSelectable(scope.row) && isCurrentBomMaterial(scope.row.materialsCode)
                  }">
                    {{ scope.row.materialsCode }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="materialsName" label="名称" width="150">
                <template #default="scope">
                  <span :class="{
                    'disabled-text': !isSelectable(scope.row) && !isCurrentBomMaterial(scope.row.materialsCode),
                    'disabled-text-current': !isSelectable(scope.row) && isCurrentBomMaterial(scope.row.materialsCode)
                  }">
                    {{ scope.row.materialsName }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="spec" label="规格" width="100">
                <template #default="scope">
                  <span :class="{
                    'disabled-text': !isSelectable(scope.row) && !isCurrentBomMaterial(scope.row.materialsCode),
                    'disabled-text-current': !isSelectable(scope.row) && isCurrentBomMaterial(scope.row.materialsCode)
                  }">
                    {{ scope.row.spec }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="itemGroupName" label="群组名称" width="120">
                <template #default="scope">
                  <span :class="{
                    'disabled-text': !isSelectable(scope.row) && !isCurrentBomMaterial(scope.row.materialsCode),
                    'disabled-text-current': !isSelectable(scope.row) && isCurrentBomMaterial(scope.row.materialsCode)
                  }">
                    {{ scope.row.itemGroupName }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pagination">
            <el-pagination v-model:current-page="leftCurrentPage" v-model:page-size="leftPageSize"
              :page-sizes="[10, 20, 50]" :total="filteredAvailableMaterials.length"
              layout="total, sizes, prev, pager, next" @size-change="handleLeftSizeChange"
              @current-change="handleLeftCurrentChange" />
          </div>
        </div>

        <!-- 中间传输按钮 -->
        <div class="transfer-buttons">
          <el-button type="primary" @click="moveToRight" :disabled="leftSelectedItems.length === 0"
            class="transfer-btn">
            <el-icon>
              <ArrowRight />
            </el-icon>
          </el-button>
          <el-button @click="moveToLeft" :disabled="rightSelectedItems.length === 0" class="transfer-btn">
            <el-icon>
              <ArrowLeft />
            </el-icon>
          </el-button>
        </div>

        <!-- 右侧编辑区域 -->
        <div class="edit-panel">
          <div class="edit-header">
            <span class="edit-title">{{ selectedMaterials.length }}项</span>
            <div class="search-box">
              <el-input v-model="rightSearchText" placeholder="请输入搜索内容" size="small" clearable>
                <template #prefix>
                  <el-icon>
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </div>
          </div>
          <div class="edit-content">
            <el-table :data="filteredSelectedMaterials" @selection-change="handleRightSelectionChange"
              class="material-table" border stripe>
              <el-table-column type="selection" width="55" />
              <el-table-column prop="materialsCode" label="编码" width="120" />
              <el-table-column prop="materialsName" label="名称" width="150" />
              <el-table-column label="工序" width="190">
                <template #default="scope">
                  <el-select v-model="scope.row.processId" placeholder="请选择工序" size="small" style="width: 100%"
                    clearable filterable>
                    <el-option v-for="process in processList" :key="process.id"
                      :label="`(${process.processCode})${process.processName}`" :value="process.id">
                      <div class="process-option">
                        <span class="process-code">{{ process.processCode }}</span>
                        <span class="process-name">{{ process.processName }}</span>
                      </div>
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="用量" width="140">
                <template #default="scope">
                  <el-input-number v-model="scope.row.useQty" :min="0" :precision="2" placeholder="请输入用量" size="small"
                    style="width: 100%" />
                </template>
              </el-table-column>
              <el-table-column label="备注" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.remark" placeholder="请输入备注" size="small" style="width: 100%" />
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="empty-state" v-if="selectedMaterials.length === 0">
            <el-icon class="empty-icon">
              <Box />
            </el-icon>
            <span>暂无数据</span>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showMaterialSelector = false">取消</el-button>
          <el-button type="primary" @click="confirmMaterialSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Upload,
  Refresh,
  Setting,
  ArrowRight,
  ArrowDown,
  ArrowLeft,
  Search,
  Box,
  Folder,
  FullScreen,
  Check
} from '@element-plus/icons-vue'
import Maxios from '@/Http/MesHelp'

// 接口定义
interface BomItem {
  id: number
  bomCode: string
  bomName: string
  version: string
  itemTypeId: number
  itemTypeName: string
  bomLevel: number
  processId: number
  processCode: string
  processName: string
  useQty: number
  bomMsg: string
  parentCode: string
  addProp: string
  addTime: string
  updTime: string
  children?: BomItem[]
}

interface MaterialItem {
  id: number
  materialsCode: string
  materialsName: string
  spec: string
  itemGroupName: string
  itemTypeId: number
  itemTypeName: string
  processId?: number
  processName?: string
  useQty?: number
  remark?: string
}

interface ProcessItem {
  id: number
  processCode: string
  processName: string
}

// 响应式数据
const loading = ref(false)
const tableLoading = ref(false)
const dialogVisible = ref(false)
const showMaterialSelector = ref(false)
const dialogTitle = ref('新增')
const isEdit = ref(false)
const bomTableRef = ref()

// 搜索表单
const searchForm = reactive({
  bomCode: ''
})

// 表单数据
const formRef = ref()
const form = reactive({
  id: 0,
  bomCode: '',
  bomName: '',
  version: '1.0',
  itemTypeId: 0,
  itemTypeName: '',
  bomLevel: 0,
  bomMsg: '',
  parentCode: '',
  addProp: localStorage.getItem('userNickname') || '',
  processId: 0, // 新增工序ID
  useQty: 1 // 新增用量
})

// 表单验证规则
const rules = {
  bomCode: [
    { required: true, message: '请选择产品物料', trigger: 'change' }
  ],
  bomName: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ]
}

// BOM表格数据
const bomTableData = ref<BomItem[]>([])

// 物料选择器数据
const availableMaterials = ref<MaterialItem[]>([])
const selectedMaterials = ref<MaterialItem[]>([])
const leftSelectedItems = ref<MaterialItem[]>([])
const rightSelectedItems = ref<MaterialItem[]>([])
const leftSearchText = ref('')
const rightSearchText = ref('')
const leftCurrentPage = ref(1)
const leftPageSize = ref(10)

// 工序数据
const processList = ref<ProcessItem[]>([])

// 当前BOM的下级数据
const currentBomChildren = ref<BomItem[]>([])

// 表单状态变量
const isCodeMatched = ref(false)  // 编码是否匹配到物料
const isNameAutoFilled = ref(false)  // 名称是否自动反填

// API基础URL
const API_BASE_URL = '/api'

// 计算属性
const filteredAvailableMaterials = computed(() => {
  if (!leftSearchText.value) return availableMaterials.value
  return availableMaterials.value.filter(item =>
    item.materialsCode.toLowerCase().includes(leftSearchText.value.toLowerCase()) ||
    item.materialsName.toLowerCase().includes(leftSearchText.value.toLowerCase())
  )
})

const filteredSelectedMaterials = computed(() => {
  if (!rightSearchText.value) return selectedMaterials.value
  return selectedMaterials.value.filter(item =>
    item.materialsCode.toLowerCase().includes(rightSearchText.value.toLowerCase()) ||
    item.materialsName.toLowerCase().includes(rightSearchText.value.toLowerCase())
  )
})

// 方法
const getTagType = (typeId: number) => {
  const typeMap: { [key: number]: string } = {
    1: 'danger',    // 原材料 - 红色
    2: 'success',   // 成品 - 绿色
    3: 'warning',   // 上工件 - 橙色
    4: 'primary'    // 半成品 - 蓝色
  }
  return typeMap[typeId] || 'info'
}

const getLevelTagType = (level: number) => {
  if (level === 0) return 'info'      // 灰色 - 顶级
  if (level === 1) return 'success'   // 绿色 - 一级
  if (level === 2) return 'warning'   // 橙色 - 二级
  if (level === 3) return 'danger'    // 红色 - 三级
  if (level === 4) return 'info'      // 灰色 - 四级
  return 'info'                       // 默认灰色
}

// 获取BOM数据
const getBomData = async () => {
  tableLoading.value = true
  try {
    const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/BomQuery`, {
      BomCode: searchForm.bomCode || null,
      BomName: null,
      Version: null,
      ItemTypeId: null,
      BomLevel: null,
      ParentCode: null,
      PageIndex: 1,
      PageSize: 1000
    })

    if (response.data.code === 200) {
      // 构建树形结构数据
      const flatData = response.data.data.data || []
      console.log('获取到的原始BOM数据:', flatData)
      bomTableData.value = buildTreeData(flatData)
      console.log('构建后的树形BOM数据:', bomTableData.value)

      // 等待DOM更新后强制展开所有节点
      await nextTick()
      if (bomTableRef.value) {
        bomTableRef.value.toggleAllSelection()
      }
    } else {
      ElMessage.error(response.data.message || '获取BOM数据失败')
    }
  } catch (error) {
    console.error('获取BOM数据失败:', error)
    // 如果API调用失败，显示错误信息但不使用模拟数据
    ElMessage.error('获取BOM数据失败，请检查网络连接')
    bomTableData.value = []
  } finally {
    tableLoading.value = false
  }
}

// 构建树形数据
const buildTreeData = (flatData: BomItem[]): BomItem[] => {
  const map = new Map<number, BomItem>()
  const result: BomItem[] = []

  console.log('开始构建树形数据，原始数据数量:', flatData.length)

  // 创建映射
  flatData.forEach(item => {
    map.set(item.id, { ...item, children: [] })
  })

  // 构建树结构
  flatData.forEach(item => {
    const node = map.get(item.id)!
    if (item.parentCode && item.parentCode.trim() !== '') {
      // 查找父节点 - 通过bomCode查找
      const parent = flatData.find(p => p.bomCode === item.parentCode)
      if (parent) {
        const parentNode = map.get(parent.id)
        if (parentNode) {
          parentNode.children!.push(node)
          console.log(`将 ${item.bomCode} 添加到父节点 ${parent.bomCode} 下`)
        }
      } else {
        // 如果找不到父节点，可能是新添加的数据，暂时作为根节点处理
        console.warn(`未找到父节点: ${item.parentCode} for item: ${item.bomCode}`)
        result.push(node)
      }
    } else {
      console.log(`将 ${item.bomCode} 作为根节点`)
      result.push(node)
    }
  })

  console.log('树形数据构建完成，根节点数量:', result.length)
  return result
}



// 获取物料数据
const getMaterials = async () => {
  try {
    const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/MaterialsQuery`, {
      MaterialsCode: null,
      MaterialsName: null,
      MaterialsMsg: null,
      Spec: null,
      Unit: null,
      ItemTypeId: null,
      ItemName: null,
      PageIndex: 1,
      PageSize: 1000
    })

    if (response.data.code === 200) {
      availableMaterials.value = response.data.data.data || []
    } else {
      ElMessage.error(response.data.message || '获取物料数据失败')
    }
  } catch (error) {
    console.error('获取物料数据失败:', error)
    ElMessage.error('获取物料数据失败，请检查网络连接')
    availableMaterials.value = []
  }
}

// 获取当前BOM的直接下级数据
const getCurrentBomChildren = async (parentCode: string) => {
  try {
    const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/BomQuery`, {
      BomCode: null,
      BomName: null,
      Version: null,
      ItemTypeId: null,
      BomLevel: null,
      ParentCode: parentCode,
      PageIndex: 1,
      PageSize: 1000
    })

    if (response.data.code === 200) {
      // 只获取直接下级，不包含孙级及以下
      const allChildren = response.data.data.data || []
      currentBomChildren.value = allChildren.filter((child: any) => child.parentCode === parentCode)
    } else {
      currentBomChildren.value = []
    }
  } catch (error) {
    console.error('获取当前BOM直接下级数据失败:', error)
    currentBomChildren.value = []
  }
}

// 获取工序数据
const getProcesses = async () => {
  try {
    const response = await Maxios.get(`${API_BASE_URL}/Process/GetProcess`, {
      params: {
        ProcessCode: null,
        ProcessName: null,
        StepTypeId: null,
        PageIndex: 1,
        PageSize: 1000
      }
    })
    if (response.data.code === 200) {
      processList.value = response.data.data.list || []
    } else {
      ElMessage.error(response.data.message || '获取工序数据失败')
    }
  } catch (error) {
    console.error('获取工序数据失败:', error)
    ElMessage.error('获取工序数据失败，请检查网络连接')
    processList.value = []
  }
}

// 搜索
const handleSearch = () => {
  getBomData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.bomCode = ''
  handleSearch()
}


// 展开全部
const expandAll = () => {
  if (!bomTableRef.value) return

  // 递归展开所有节点
  const expandAllRows = (data: BomItem[]) => {
    data.forEach(row => {
      if (row.children && row.children.length > 0) {
        bomTableRef.value.toggleRowExpansion(row, true)
        expandAllRows(row.children)
      }
    })
  }

  expandAllRows(bomTableData.value)
  ElMessage.success('已展开全部节点')
}

// 折叠全部
const collapseAll = () => {
  if (!bomTableRef.value) return

  // 递归折叠所有节点
  const collapseAllRows = (data: BomItem[]) => {
    data.forEach(row => {
      if (row.children && row.children.length > 0) {
        bomTableRef.value.toggleRowExpansion(row, false)
        collapseAllRows(row.children)
      }
    })
  }

  collapseAllRows(bomTableData.value)
  ElMessage.success('已折叠全部节点')
}

// 刷新数据
const refreshData = () => {
  getBomData()
  ElMessage.success('数据已刷新')
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增'
  dialogVisible.value = true
  resetForm()
}

// 编辑
const handleEdit = (row: BomItem) => {
  isEdit.value = true
  dialogTitle.value = '编辑'
  dialogVisible.value = true

  Object.assign(form, {
    id: row.id,
    bomCode: row.bomCode,
    bomName: row.bomName,
    version: row.version,
    itemTypeId: row.itemTypeId,
    bomLevel: row.bomLevel,
    bomMsg: row.bomMsg,
    parentCode: row.parentCode,
    addProp: row.addProp,
    processId: row.processId, // 填充工序ID
    useQty: row.useQty // 填充用量
  })

  // 检查编码是否匹配到物料，设置状态变量
  const selectedMaterial = availableMaterials.value.find(
    (material) => material.materialsCode === row.bomCode
  );
  if (selectedMaterial) {
    isCodeMatched.value = true;
    isNameAutoFilled.value = true;
  } else {
    isCodeMatched.value = false;
    isNameAutoFilled.value = false;
  }
}

// 删除
const handleDelete = async (row: BomItem) => {
  try {
    await ElMessageBox.confirm('确定要删除这个BOM吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/BomDel`, {
      Id: row.id
    })

    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      getBomData()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 添加下级
const handleAddSub = (row: BomItem) => {
  showMaterialSelector.value = true
  form.parentCode = row.bomCode
  // 清空之前的选择
  selectedMaterials.value = []
  leftSelectedItems.value = []
  rightSelectedItems.value = []
  leftSearchText.value = ''
  rightSearchText.value = ''
  // 获取当前BOM的下级数据
  getCurrentBomChildren(row.bomCode)
}

// 绑定产品
const handleBindProduct = (row: BomItem) => {
  ElMessage.info('绑定产品功能开发中...')
}

// 导入
const handleImport = () => {
  // 创建文件输入元素
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.xlsx,.xls'
  input.onchange = async (event) => {
    const file = (event.target as HTMLInputElement).files?.[0]
    if (!file) return

    try {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('skipErrors', 'false')
      formData.append('importUser', localStorage.getItem('userNickname') || 'System')

      const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/BomImport`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      if (response.data.code === 200) {
        const result = response.data.data
        ElMessage.success(`导入完成！成功：${result.successCount}条，失败：${result.failCount}条`)

        if (result.failCount > 0) {
          console.log('导入错误信息:', result.errorMessages)
          // 可以显示详细的错误信息
          ElMessage.warning(`有${result.failCount}条数据导入失败，请检查数据格式`)
        }

        // 刷新数据
        getBomData()
      } else {
        ElMessage.error(response.data.message || '导入失败')
      }
    } catch (error) {
      console.error('导入失败:', error)
      ElMessage.error('导入失败，请检查文件格式')
    }
  }
  input.click()
}

// 导出
const handleExport = async () => {
  try {
    const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/BomExport`, {
      BomCode: searchForm.bomCode || null,
      BomName: null,
      Version: null,
      ItemTypeId: null,
      BomLevel: null,
      ParentCode: null,
      ExportAll: true,
      PageIndex: 1,
      PageSize: 1000
    }, {
      responseType: 'blob'
    })

    // 创建下载链接
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `BOM数据_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}



// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    const requestData = {
      Id: form.id || 0,
      BomCode: form.bomCode,
      BomName: form.bomName,
      Version: form.version,
      ItemTypeId: form.itemTypeId,
      BomLevel: form.bomLevel,
      BomMsg: form.bomMsg || '',
      ParentCode: form.parentCode,
      AddProp: localStorage.getItem('userNickname') || '',
      UpdProp: isEdit.value ? localStorage.getItem('userNickname') || '' : '',
      ProcessId: form.processId || 0, // 新增工序ID
      UseQty: form.useQty || 1 // 新增用量
    }

    if (isEdit.value) {
      const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/BomUp`, requestData)
      if (response.data.code === 200) {
        ElMessage.success(response.data.message || '更新成功')
      } else {
        ElMessage.error(response.data.message || '更新失败')
        return
      }
    } else {
      const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/BomAdd`, requestData)
      if (response.data.code === 200) {
        ElMessage.success(response.data.message || '添加成功')
      } else {
        ElMessage.error(response.data.message || '添加失败')
        return
      }
    }

    dialogVisible.value = false
    getBomData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: 0,
    bomCode: '',
    bomName: '',
    version: '1.0',
    itemTypeId: 0,
    bomLevel: 0,
    bomMsg: '',
    parentCode: '',
    addProp: localStorage.getItem('userNickname') || '',
    processId: 0, // 重置工序ID
    useQty: 1 // 重置用量
  })

  // 重置状态变量
  isCodeMatched.value = false
  isNameAutoFilled.value = false
}

// 物料选择器相关方法
const refreshMaterials = () => {
  getMaterials()
  ElMessage.success('物料数据已刷新')
}

const handleLeftSelectionChange = (selection: MaterialItem[]) => {
  leftSelectedItems.value = selection
}

const handleRightSelectionChange = (selection: MaterialItem[]) => {
  rightSelectedItems.value = selection
}

const moveToRight = () => {
  leftSelectedItems.value.forEach(item => {
    if (!selectedMaterials.value.find(selected => selected.id === item.id)) {
      selectedMaterials.value.push({
        ...item,
        processId: 0,
        processName: '',
        useQty: 1,
        remark: ''
      })
    }
  })
  // 清空左边选择，实现"左边暂时消失"的效果
  leftSelectedItems.value = []
}

const moveToLeft = () => {
  rightSelectedItems.value.forEach(item => {
    const index = selectedMaterials.value.findIndex(selected => selected.id === item.id)
    if (index > -1) {
      selectedMaterials.value.splice(index, 1)
    }
  })
  rightSelectedItems.value = []
}

const handleLeftSizeChange = (size: number) => {
  leftPageSize.value = size
  leftCurrentPage.value = 1
}

const handleLeftCurrentChange = (page: number) => {
  leftCurrentPage.value = page
}

const confirmMaterialSelection = async () => {
  if (selectedMaterials.value.length === 0) {
    ElMessage.warning('请选择至少一个物料')
    return
  }

  // 验证选中的物料是否都填写了必要信息
  const invalidItems = selectedMaterials.value.filter(item =>
    !item.processId || !item.useQty || item.useQty <= 0
  )

  if (invalidItems.length > 0) {
    ElMessage.warning('请为所有选中的物料填写工序和用量')
    return
  }

  try {
    // 获取父级BOM信息，用于计算阶别
    let parentBom: BomItem | null = null

    // 在树形结构中查找父级BOM
    for (const rootItem of bomTableData.value) {
      parentBom = findBomInTree(rootItem, form.parentCode)
      if (parentBom) {
        break
      }
    }

    if (!parentBom) {
      ElMessage.error('未找到父级BOM信息')
      return
    }

    // 计算新的阶别（父级阶别 + 1）
    const newBomLevel = parentBom.bomLevel + 1

    // 批量添加BOM下级
    const promises = selectedMaterials.value.map(async (material) => {
      const requestData = {
        Id: 0,
        BomCode: material.materialsCode,
        BomName: material.materialsName,
        Version: '1.0',
        ItemTypeId: material.itemTypeId,
        BomLevel: newBomLevel,
        BomMsg: material.remark || '',
        ParentCode: form.parentCode,
        AddProp: localStorage.getItem('userNickname') || '',
        UpdProp: '',
        ProcessId: material.processId,
        UseQty: material.useQty
      }

      return Maxios.post(`${API_BASE_URL}/ItemGroup/BomAdd`, requestData)
    })

    const responses = await Promise.all(promises)

    // 检查所有请求是否成功
    const failedResponses = responses.filter(response => response.data.code !== 200)

    if (failedResponses.length > 0) {
      ElMessage.error('部分物料添加失败，请重试')
      return
    }

    ElMessage.success(`成功添加 ${selectedMaterials.value.length} 个下级物料`)
    showMaterialSelector.value = false

    // 刷新BOM数据
    await getBomData()

    // 等待DOM更新后强制展开所有节点
    await nextTick()
    if (bomTableRef.value) {
      // 强制展开所有节点
      const expandAllRows = (data: BomItem[]) => {
        data.forEach(row => {
          if (row.children && row.children.length > 0) {
            bomTableRef.value.toggleRowExpansion(row, true)
            expandAllRows(row.children)
          }
        })
      }
      expandAllRows(bomTableData.value)
    }

    // 清空选择的数据
    selectedMaterials.value = []
    leftSelectedItems.value = []
    rightSelectedItems.value = []
    currentBomChildren.value = []

  } catch (error) {
    console.error('添加下级失败:', error)
    ElMessage.error('添加下级失败，请重试')
  }
}



// 编码选择器变化时触发
const handleCodeChange = (value: string) => {
  const selectedMaterial = availableMaterials.value.find(
    (material) => material.materialsCode === value
  );
  if (selectedMaterial) {
    // 自动反填名称
    form.bomName = selectedMaterial.materialsName;
    form.itemTypeId = selectedMaterial.itemTypeId;
    form.itemTypeName = selectedMaterial.itemTypeName;
    isCodeMatched.value = true;
    isNameAutoFilled.value = true;
  } else {
    // 清空相关字段
    form.bomName = '';
    form.itemTypeId = 0;
    form.itemTypeName = '';
    isCodeMatched.value = false;
    isNameAutoFilled.value = false;
  }
};

// 在树形结构中查找BOM
const findBomInTree = (node: BomItem, bomCode: string): BomItem | null => {
  if (node.bomCode === bomCode) {
    return node
  }

  if (node.children && node.children.length > 0) {
    for (const child of node.children) {
      const found = findBomInTree(child, bomCode)
      if (found) {
        return found
      }
    }
  }

  return null
}

// 检查物料是否为当前正在添加下级的BOM本身
const isCurrentBomMaterial = (materialsCode: string): boolean => {
  // 检查是否为当前正在添加下级的BOM本身
  if (form.parentCode === materialsCode) {
    console.log(`物料 ${materialsCode} 是当前正在添加下级的BOM本身，将被禁用`)
    return true
  }
  return false
}

// 判断物料是否可选中
const isSelectable = (row: MaterialItem) => {
  // 如果右侧已选物料中已包含该物料，则不可选中
  if (selectedMaterials.value.some(item => item.id === row.id)) {
    return false
  }

  // 检查该物料是否已存在于当前BOM的直接下级中
  if (currentBomChildren.value.length > 0) {
    const isExistingDirectChild = currentBomChildren.value.some(child => child.bomCode === row.materialsCode)
    if (isExistingDirectChild) {
      return false // 已存在的直接下级禁用选择
    }
  }

  // 检查该物料是否为当前正在添加下级的BOM本身
  if (isCurrentBomMaterial(row.materialsCode)) {
    return false // 当前BOM本身禁用选择
  }

  return true
};

// 获取表格行的类名
const getRowClassName = ({ row }: { row: MaterialItem }) => {
  if (!isSelectable(row)) {
    // 如果是因为是当前BOM本身而被禁用，使用不同的样式
    if (isCurrentBomMaterial(row.materialsCode)) {
      return 'disabled-row-current'
    }
    return 'disabled-row'
  }
  return ''
};

// 生命周期
onMounted(() => {
  getBomData()
  getMaterials()
  getProcesses() // 获取工序数据
})
</script>

<style scoped>
.bom-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 15px;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-item label {
  font-weight: 500;
  color: #333;
  min-width: 60px;
}

.search-input {
  width: 200px;
}

.search-actions {
  display: flex;
  gap: 10px;
}

.action-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

.left-actions {
  display: flex;
  gap: 10px;
}

.right-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.main-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.table-container {
  padding: 0;
  overflow-x: auto;
  max-width: 100%;
  background-color: #f5f5f5;
}

.data-table {
  width: 100%;
  min-width: 1600px;
  background-color: white;
}

/* 自定义滚动条样式 */
.table-container::-webkit-scrollbar {
  height: 8px;
}

.table-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.table-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.table-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 表格样式 */
:deep(.el-table) {
  border: none;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
  border-bottom: 1px solid #e9ecef;
  height: 50px;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
  height: 50px;
  color: #666;
  background-color: white;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

/* 编码列样式 */
.code-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 标签样式 */
.type-tag {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

.type-tag.el-tag--danger {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fbc4c4;
}

.type-tag.el-tag--success {
  background-color: #f0f9ff;
  color: #67c23a;
  border: 1px solid #c2e7b0;
}

.type-tag.el-tag--warning {
  background-color: #fdf6ec;
  color: #e6a23c;
  border: 1px solid #f5dab1;
}

.type-tag.el-tag--primary {
  background-color: #ecf5ff;
  color: #409eff;
  border: 1px solid #b3d8ff;
}

.type-tag.el-tag--info {
  background-color: #f4f4f5;
  color: #909399;
  border: 1px solid #d3d4d6;
}

.level-tag {
  font-size: 12px;
  padding: 2px 8px;
  min-width: 24px;
  text-align: center;
}

.level-tag.el-tag--success {
  background-color: #67c23a;
  color: white;
  border: none;
}

.level-tag.el-tag--primary {
  background-color: #409eff;
  color: white;
  border: none;
}

.level-tag.el-tag--info {
  background-color: #909399;
  color: white;
  border: none;
}

.level-tag.el-tag--warning {
  background-color: #e6a23c;
  color: white;
  border: none;
}

.level-tag.el-tag--danger {
  background-color: #f56c6c;
  color: white;
  border: none;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-link {
  color: #409eff;
  text-decoration: none;
  font-size: 12px;
  padding: 2px 4px;
  border-radius: 2px;
  transition: all 0.3s;
}

.action-link:hover {
  background-color: #f0f9ff;
}

.delete-link {
  color: #f56c6c;
}

.delete-link:hover {
  background-color: #fef0f0;
}

/* 图标样式 */
.refresh-icon,
.setting-icon,
.fullscreen-icon {
  font-size: 16px;
  color: #606266;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.refresh-icon:hover,
.setting-icon:hover,
.fullscreen-icon:hover {
  color: #409eff;
  background-color: #f0f9ff;
}

/* 双列选择器样式 */
.dual-panel-container {
  display: flex;
  gap: 20px;
  height: 500px;
}

.list-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.edit-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f8f9fa;
}

.list-panel .panel-header {
  padding: 10px 15px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.legend {
  display: flex;
  gap: 15px;
  font-size: 12px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  display: inline-block;
}

.legend-color.disabled-text {
  background-color: #c0c4cc;
}

.legend-color.disabled-text-current {
  background-color: #e6a23c;
}

.item-count {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.search-box {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-box .el-input {
  width: 200px;
}

.table-container {
  flex: 1;
  overflow-y: auto;
}

.material-table {
  width: 100%;
}

.pagination {
  padding: 10px 15px;
  border-top: 1px solid #e9ecef;
  background-color: #f8f9fa;
}

.transfer-buttons {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 20px;
  padding: 0 20px;
}

.transfer-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}

.transfer-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 14px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

/* 编辑面板样式 */
.edit-panel .edit-header {
  padding: 10px 15px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.edit-title {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.edit-content {
  flex: 1;
  overflow-y: auto;
}

/* 物料选项样式 */
.material-option {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.option-tag {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
  flex-shrink: 0;
}

.material-name {
  font-size: 14px;
  color: #333;
  flex: 1;
}

/* 工序选项样式 */
.process-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.process-code {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.process-name {
  font-size: 12px;
  color: #333;
}

/* 表单样式 */
.bom-form {
  padding: 20px 0;
}

/* 编码输入框样式 */
.bom-form .el-form-item__content .el-input {
  position: relative;
}

/* 当编码匹配到物料时的样式 */
.bom-form .el-form-item__content .el-input.is-matched .el-input__wrapper {
  border-color: #67c23a;
  box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.2);
}

/* 名称输入框样式 */
.bom-form .el-form-item__content .el-input.is-auto-filled .el-input__wrapper {
  background-color: #f0f9ff;
  border-color: #409eff;
}

/* 自动反填的提示样式 */
.auto-fill-hint {
  font-size: 12px;
  color: #67c23a;
  margin-top: 4px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.auto-fill-hint .el-icon {
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 0;
}

/* 禁用行样式 */
.disabled-row {
  background-color: #f5f5f5 !important;
  color: #c0c4cc !important;
}

.disabled-row:hover {
  background-color: #f5f5f5 !important;
}

/* 当前BOM的禁用行样式 */
.disabled-row-current {
  background-color: #fff7e6 !important;
  color: #e6a23c !important;
}

.disabled-row-current:hover {
  background-color: #fff7e6 !important;
}

.disabled-text {
  color: #c0c4cc !important;
}

/* 当前BOM的禁用文本样式 */
.disabled-text-current {
  color: #e6a23c !important;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .action-row {
    flex-direction: column;
    align-items: stretch;
  }

  .right-actions {
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .search-row {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input {
    width: 100%;
  }

  .dual-panel-container {
    flex-direction: column;
    height: auto;
  }
}
</style>
